﻿// VIEW MODEL
var viewModel = {

    // status dropdown
    status: ko.observableArray([]),
    selectedStatus: ko.observable(),

    // category dropdown
    categories: ko.observableArray([]),
    selectedCategory: ko.observable(),

    // person dropdown
    people: ko.observableArray([]),
    selectedPerson: ko.observable(),

    // model properties
    Id:             ko.observable(),
    ModuleId:       ko.observable(0),
    CreatedDate:    ko.observable(),
    CreatedByUser:  ko.observable(1),
    Task:           ko.observable(""),

    loadStatus: function () {
        OData.read(_serviceURL + "/ToDoListStatus",
            function (data) {
                viewModel.status.removeAll();
                $.each(data.results, function (index, item) {
                    viewModel.status.push(ko.mapping.fromJS(item));
                });
            });
    },

    loadCategories: function () {
        OData.read(_serviceURL + "/ToDoListCategories",
            function (data) {
                viewModel.categories.removeAll();
                $.each(data.results, function (index, item) {
                    viewModel.categories.push(ko.mapping.fromJS(item));
                });
            });
    },

    loadPeople: function () {
        OData.read(_serviceURL + "/Users",
            function (data) {
                viewModel.people.removeAll();
                $.each(data.results, function (index, item) {
                    viewModel.people.push(ko.mapping.fromJS(item));
                });
            });
    },

    addTask: function () {

        var _postData = {
            Id: viewModel.Id(),
            ModuleId: viewModel.ModuleId(),
            CreatedDate: new Date(),
            Task: viewModel.Task(),
            Category: { __metadata: {uri: "/ToDoListCategories(" + viewModel.selectedCategory() + ")"} },
            Status: { __metadata: {uri: "/ToDoListStatus(" + viewModel.selectedStatus() + ")"} },
            User: { __metadata: {uri: "/Users(" + viewModel.selectedPerson() + ")"} }
        };

        var _request = {
            requestUri: _serviceURL + "/ToDoListItems",
            method: "POST",
            data: _postData
        };

        OData.request(_request, function (data) {
            document.location.href = _returnURL;
        });

    },

    cancelTask: function () {
        var _confirm = confirm("Are you sure you want to Cancel?")
        if (_confirm) {
            document.location.href = _returnURL;
        }
    }

};

ko.applyBindings(viewModel);

viewModel.loadStatus();
viewModel.loadCategories();
viewModel.loadPeople();
